package com.icefish.control;

import com.alibaba.fastjson.JSONObject;
import com.icefish.bean.Comment;
import com.icefish.bean.fastjsonParse.Meta;
import com.icefish.bean.fastjsonParse.addComment.AddCommentResp;
import com.icefish.dao.CommentDao;
import com.icefish.daoFactory.DaoFactory;
import com.icefish.utils.DateTransform;
import com.icefish.utils.Init_Req_Resp_Config;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet("/addComment")
public class addComment extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Init_Req_Resp_Config.init(request, response);

//        String says_time = request.getParameter("says_time");
//        时间不允许客户端传，由服务器生成
        Date says_time = new Date();
        String says = request.getParameter("says");
        String goods_id = request.getParameter("goods_id");
        String user_id = request.getParameter("user_id");
        String username = request.getParameter("username");
        String order_id = request.getParameter("order_id");

        Comment comment = new Comment();

        comment.setSays_time(says_time);
        comment.setSays(says);
        comment.setGoods_id(Integer.parseInt(goods_id));
        comment.setUser_id(Integer.parseInt(user_id));
        comment.setUsername(username);
        comment.setOrder_id(Integer.parseInt(order_id));

        boolean isok = false;
        // 1、调用CommentDao.addComment方法，进行添加评论
        try {
            CommentDao cd = DaoFactory.getCommentDaoInstance();
            isok = cd.addComment(comment);
        } catch (Exception e) {
            e.printStackTrace();
        }

        AddCommentResp acr = null;
        // 2、添加成功，返回评论数据
        if (isok) {
            acr = new AddCommentResp(says,new Meta("添加评论成功",200));
        }
        // 3、添加失败，返回错误信息
        else {
            acr = new AddCommentResp("添加评论失败",new Meta("添加评论失败",500));
        }

        JSONObject jsonObject = new JSONObject();
        // 转换成json
        String backToBrowser = jsonObject.toJSONString(acr);

        // 响应数据
        response.getWriter().write(backToBrowser);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
